<?php

class UserAction extends PublicAction
{
    protected $userId;
    protected $usersModel;

    function _initialize()
    {
        parent::_initialize();
        //检测用户是否登陆
        $this->checkLogin();
        $this->userId = $_SESSION['user']['id'];
        $this->usersModel = M('User');
    }

    public function index()
    {
        $user = M('User')->find($this->userId);
        $this->assign('user',$user);

        $role = F('UserGroup');
        $this->assign('role',$role);
        $this->display();
    }

    public function baseinfo()
    {
        if (IS_POST) {
            $_POST['id'] = $this->userId;
            if (!$this->usersModel->create($_POST)) {
                $this->error($this->usersModel->getError());
            }
            $this->usersModel->update_time = time();
            $this->usersModel->last_ip = get_client_ip();
            $result = $this->usersModel->save();
            if(false !== $result) {
                $this->success('保存成功！');
            }else{
                $this->error('保存失败！');
            }
            exit;
        }
        $user = $this->usersModel->find($this->userId);
        $this->assign('user',$user);
        $this->display();
    }

    public function avatar()
    {
        if (IS_POST) {
            $_POST['id'] = $this->userId;

            if(!empty($_FILES['pic']['name'])){
                import('ORG.Net.UploadFile');
                $upload = new UploadFile();// 实例化上传类
                $upload->maxSize  = 3145728 ;// 设置附件上传大小
                $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
                $upload->savePath =  UPLOAD_PATH;// 设置附件上传目录
                $upload->thumb = true;
                $upload->thumbMaxWidth = '204';
                $upload->thumbMaxHeight = '298';
                if (!$upload->upload()) {// 上传错误提示错误信息
                    $this->error($upload->getErrorMsg());
                } else {// 上传成功 获取上传文件信息
                    $info = $upload->getUploadFileInfo();
                    $_POST['image'] = $info[0]['savename'];
                    $_POST['avatar'] = 'thumb_'.$info[0]['savename'];
                }
            }

            $this->usersModel->update_time = time();
            $this->usersModel->avatar = $_POST['avatar'];
            $this->usersModel->last_ip = get_client_ip();
            $result = $this->usersModel->save();

            if(false !== $result) {
                $this->success('修改成功！');
            }else{
                $this->error('修改失败！');
            }
            exit;
        }

        $this->display();
    }

    public function updatepwd()
    {
        if(IS_POST){
            if($_POST['password'] != $_POST['repassword']){
                $this->error('两次密码不一致！');
            }

            $map = array();
            $map['password']= sysmd5($_POST['oldpassword']);
            $map['id'] = $this->userId;
            $map['username'] = $_SESSION['user']['username'];

            //检查用户
            if(!$this->usersModel->where($map)->field('id')->find()) {
                $this->error('旧密码错误！');
            }else {
                $this->usersModel->email = $_POST['email'];
                $this->usersModel->id = $this->userId;
                $this->usersModel->update_time = time();
                $this->usersModel->password = sysmd5($_POST['password']);
                $r = $this->usersModel->save();
                $this->assign('jumpUrl',U('Account/password'));
                if($r){
                    $this->success('修改成功！');
                }else{
                    $this->error('修改失败！');
                }
            }
            exit;
        }
        $this->display();
    }

    //上传头像
    public function uploadImg()
    {
        import('ORG.Net.UploadFile');
        $upload = new UploadFile();                     // 实例化上传类
        $upload->maxSize = 1*1024*1024;                 //设置上传图片的大小
        $upload->allowExts = array('jpg','png','gif');  //设置上传图片的后缀
        $upload->uploadReplace = true;                  //同名则替换

        //完整的头像路径
        $path = UPLOAD_PATH.'avatar/';
        $upload->savePath = $path;
        if(!$upload->upload()) {                        // 上传错误提示错误信息
            $this->ajaxReturn('',$upload->getErrorMsg(),0,'json');
        }else{                                          // 上传成功 获取上传文件信息
            $info =  $upload->getUploadFileInfo();
            $_POST['image'] = $info[0]['savename'];
            $temp_size = getimagesize($path.$_POST['image']);
            if($temp_size[0] < 100 || $temp_size[1] < 100){//判断宽和高是否符合头像要求
                $this->ajaxReturn(0,'图片宽或高不得小于100px！',0,'json');
            }
            $this->ajaxReturn('/uploads/avatar/'.$_POST['image'],$info,1,'json');
        }
    }


    //裁剪并保存用户头像
    public function cropImg()
    {
        //图片裁剪数据
        $params = I('post.');                       //裁剪参数
        if(!isset($params) && empty($params)){
            return;
        }

        //要保存的图片
        $pic_path = $real_path = '.'.$params['src'];

        import('ORG.Util.Image.ThinkImage');
        $Think_img = new ThinkImage(THINKIMAGE_GD);
        //裁剪原图
        $Think_img->open($pic_path)->crop($params['w'],$params['h'],$params['x'],$params['y'])->save($real_path);
        //生成缩略图
        $Think_img->open($real_path)->thumb(100,100, 1)->save($real_path);

        $data['id'] = $this->userId;
        $data['update_time'] = time();
        $data['avatar'] = $params['src'];
        $data['last_ip'] = get_client_ip();
        $this->usersModel->save($data);

        $_SESSION['user']['avatar'] = $params['src'];
        $this->success('上传头像成功');
    }

    public function logistics()
    {
        if (IS_POST) {
            header('Content-Type:text/html; charset=utf-8');

            $express_num = isset($_POST['express_num']) ? trim($_POST['express_num']) : "";
            $type = $_POST['type'];
            //$express_code = isset($_POST['express_code']) ? trim($_POST['express_code']) : "";
            if ($express_num) {
                $url = "http://www.kuaidi100.com/query?type=". $type . "&postid=" . $express_num . "&id=1&valicode=&temp=". time() . rand(100000, 999999);
                $kuaidis = getUrlJson($url,1);
                if ($kuaidis) {
                    echo json_encode($kuaidis);
                } else {
                    echo json_encode(array("code" => 'noquery', "reason" => "该快递号查询不到！"));
                }
            } else {
                echo json_encode(array("code" => 'param', "reason" => "缺少必要参数！"));
            }
            exit;
        }
        $codes = array(
            0=>array(
                "code"=>"ems",
                "name"=>"ems快递",
            ),
            1=>array(
                "code"=>"shentong",
                "name"=>"申通快递",
            ),
            2=>array(
                "code"=>"yuantong",
                "name"=>"圆通速递",
            ),
            3=>array(
                "code"=>"shunfeng",
                "name"=>"顺丰速运",
            ),
            4=>array(
                "code"=>"tiantian",
                "name"=>"天天快递",
            ),
            5=>array(
                "code"=>"yunda",
                "name"=>"韵达快递",
            ),
            6=>array(
                "code"=>"zhongtong",
                "name"=>"中通速递",
            ),
            7=>array(
                "code"=>"longbanwuliu",
                "name"=>"龙邦物流",
            ),
            8=>array(
                "code"=>"zhaijisong",
                "name"=>"宅急送",
            ),
            9=>array(
                "code"=>"quanyikuaidi",
                "name"=>"全一快递",
            ),
            10=>array(
                "code"=>"huitongkuaidi",
                "name"=>"汇通速递",
            ),
            11=>array(
                "code"=>"minghangkuaidi",
                "name"=>"民航快递",
            ),
            12=>array(
                "code"=>"yafengsudi",
                "name"=>"亚风速递",
            ),
            13=>array(
                "code"=>"kuaijiesudi",
                "name"=>"快捷速递",
            ),
            14=>array(
                "code"=>"tiandihuayu",
                "name"=>"天地华宇",
            ),
            15=>array(
                "code"=>"zhongtiekuaiyun",
                "name"=>"中铁快运",
            ),
            16=>array(
                "code"=>"deppon",
                "name"=>"德邦物流",
            ),
            17=>array(
                "code"=>"yousukuaidi",
                "name"=>"优速快递",
            ),
            18=>array(
                "code"=>"yeahyoung",
                "name"=>"越洋仓国际供应链",
            ),
        );

        $this->assign('codes', $codes);
        $this->display();
    }


    public function collection()
    {
        $data = D('Collection')->where('user_id='.session('user.id'))->getField('goods_id',true);

        $list = D('Goods')->where(['id'=>['in',$data]])->select();

        $this->assign('list', $list);
        $this->display();
    }

    public function collectionAdd()
    {
        $uid = session('user.id');
        $id = I('id', 0, 'intval');
        $data['goods_id'] = $id;
        $data['user_id'] = $uid;

        if (M('collection')->where($data)->find()) {
            $this->error('您已经收藏过！');
        } else {
            $data['create_time'] = time();
            M('collection')->add($data);
            $this->success('收藏成功！');
        }
    }


    public function cancelCollection()
    {
        $uid = session('user.id');

        $id = I('id', 0, 'intval');

        $data['goods_id'] = $id;
        $data['user_id'] = $uid;

        if (D('collection')->where($data)->delete()) {
            $this->success('取消收藏成功！');
        }
    }

    function address()
    {
        $address_db = D('UserAddress');

        $area = M('Area')->getField('id,name');
        $this->assign('area', $area);

        $list = $address_db->where('user_id=' . $this->userId)->select();
        $this->assign('list', $list);
        $this->display();
    }

    function addressAdd()
    {
        if (IS_POST) {
            $address_db = D('UserAddress');
            $_POST['user_id'] = $this->userId;

            if (!$address_db->create()) {
                $this->error($address_db->getError());
            }
            $result = $address_db->add();
            if (false !== $result) {
                $this->success('新增成功！');
            } else {
                $this->error('新增失败！');
            }
        } else {
            $this->display();
        }
    }

    public function addressEdit()
    {
        $model = D('UserAddress');

        if (IS_POST) {

            if (false === $model->create()) {
                $this->error($model->getError());
            }

            // 更新数据
            $list = $model->save();

            if (false !== $list) {
                $this->success('保存成功！');
            } else {
                //错误提示
                $this->error('保存失败: ' . $model->getDbError());
            }
        } else {
            $id = I('id');
            $adr = $model->getById($id);

            $this->assign('adr', $adr);
            $this->display();
        }
    }


    function addressDel()
    {
        $model = M('UserAddress');
        $id = I('get.id', 0, 'intval');

        if (isset($id)) {
            if (false !== $model->delete($id)) {
                $this->success('删除成功！');
            } else {
                $this->error('删除失败: ' . $model->getDbError());
            }
        } else {
            $this->error(L('do_empty'));
        }
    }

    //设为默认地址
    public function setDefault()
    {
        $id = I('id', 0, 'intval');
        if (!$id) {
            $this->error('非法参数！');
        }

        $model = D('UserAddress');
        $model->where(array('user_id' => $this->userId))->save(array('is_default' => 0));
        $model->where(array(
            'id'      => $id,
            'user_id' => $this->userId
        ))->save(array('is_default' => 1));
        $this->success('设置成功！');
    }
}